package com.loyal.camerax.ui.camera

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.navigation.NavOptions
import androidx.navigation.contains
import androidx.navigation.fragment.findNavController
import com.loyal.camerax.R
import com.loyal.camerax.utils.ActivityHelper.hasPermissions
import com.loyal.camerax.utils.PermissionHelper

class PermissionsFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!requireContext().hasPermissions(PERMISSIONS_REQUIRED)) {
            permissionsLauncher.launch(PERMISSIONS_REQUIRED)
        } else {
            navigateToCamera()
        }
    }

    private fun navigateToCamera() {
        /*lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                val action = PermissionsFragmentDirections.actionToCamera()
                findNavController().navigate(action)
            }
        }*/

        val navIdRes = activity?.intent?.getIntExtra(CameraFragmentActivity.CAMERA_ID_RES, -1) ?: -1
        Log.e(TAG, "navigateToCamera: $navIdRes")
        val navController = findNavController()
        val navGraph = navController.graph
        navGraph.let {
            val hasNavIdRes = it.contains(navIdRes)
            if (hasNavIdRes) {
                val options = NavOptions.Builder()
                    .setPopUpTo(R.id.permission_fragment, inclusive = true)
                    .build()
                navController.navigate(navIdRes, null, options)
            }
        }
    }

    private val permissionsLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { refused ->
            var permissionGranted = true
            refused.entries.forEach {
                if (it.key in PERMISSIONS_REQUIRED && !it.value)
                    permissionGranted = false
            }
            if (!permissionGranted) {
                Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show()
            } else {
                navigateToCamera()
            }
        }

    companion object {
        private const val TAG = "PermissionsFragment"
        private val PERMISSIONS_REQUIRED = PermissionHelper.all()
    }
}